# == Schema Information
#
# Table name: sales_follow_ups
#
#  id                    :integer          not null, primary key
#  firm_id               :integer
#  contact_id            :integer
#  leads_type            :integer
#  follow_up_type        :integer
#  appointment_time      :datetime
#  completed_at          :datetime
#  content               :string(255)
#  user_id               :integer
#  created_by            :integer
#  completed_by          :integer
#  follow_up_target_type :integer
#  created_at            :datetime         not null
#  updated_at            :datetime         not null
#

class Sales::FollowUp < ApplicationRecord
  extend Enumerize

  belongs_to :user, :class_name => 'Base::User', foreign_key: 'user_id'
  belongs_to :complete_user, :class_name => 'Base::User', foreign_key: 'completed_by'
  belongs_to :create_user, :class_name => 'Base::User', foreign_key: 'creted_by'

  belongs_to :firm, :class_name => 'Sales::Firm', foreign_key: 'firm_id'
  belongs_to :contact, :class_name => 'Sales::Contact', foreign_key: 'contact_id'

  FOLLOW_UP_TYPE = { meet: 1, mail: 2, phone: 3, msg: 4, other: 5 }.freeze
  enumerize :follow_up_type, in: FOLLOW_UP_TYPE,  predicates: { prefix: true }, scope: true

  TARGET_TYPE = { normal: 1, sale: 2, renew: 3, other: 4 }.freeze
  enumerize :follow_up_target_type, in: TARGET_TYPE, predicates: { prefix: true }, scope: true

  enumerize :leads_type, in: ::Sales::FirmLead::LEADS_TYPE, predicates: {prefix: true}, scope: true

  before_save :set_complete

  attr_accessor :is_completed

  validates_presence_of :appointment_time, message: '请输入安排时间'
  validates_presence_of :follow_up_target_type, message: '请选择跟进目的'
  validates_presence_of :follow_up_type, message: '请选择跟进方式'

  def completed?
    completed_at.present?
  end

  def set_complete
    if is_completed.to_i == 1
      self.completed_at ||= Time.now
      self.completed_by ||= Base::Session.current_user_id
    end
  end

  def calendar_attr
    # if appointment_time >= appointment_time.at_beginning_of_day
    #
    # end
    {
        start: appointment_time.label,
        end: (appointment_time+1.hour).label,
        title: "#{firm.name} -- #{follow_up_type_text}(#{follow_up_target_type_text})",
        user_id: user_id, firm_id: firm_id,id: id,
        color: completed_at.present? ? '#32ccfe' : 'blueviolet',
        completed_at: completed_at, is_completed: completed_at.present?

    }
  end

end
